package cn.edu.xjtu.android.emoji_warfare_android;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

/**
 * EndActivity<br>
 * 游戏结束界面
 * 
 * @author wyyf
 *
 */
public class EndActivity extends Activity {
    long time;
    ImageView im;
    Button oneMore;
    Button quit;
    TextView text;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_end);

        time = getIntent().getLongExtra("time", -1);

        // 防止意外回调
        if (time < 0) {
            finish();
        }

        im = (ImageView) findViewById(R.id.imageView1);
        oneMore = (Button) findViewById(R.id.button1);
        quit = (Button) findViewById(R.id.button2);
        text = (TextView) findViewById(R.id.textView1);

        oneMore.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View arg0) {
                Intent t = new Intent(EndActivity.this, StartActivity.class);
                startActivity(t);
                finish();
            }
        });
        quit.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View arg0) {
                EndActivity.this.finish();
            }
        });
        App app = (App) getApplication();
        im.setImageBitmap(app.screenShot);

        text.setText("你击败了" + (getIntent().getIntExtra("waveIndex", -1) - 2) + "波敌人");

        im.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                saveBitmap();
            }
        });

    }

    public final int REQUEST_CODE_CONTACT = 101;

    @SuppressLint("NewApi")
    private boolean requestPermissions() {
        boolean flag = true;
        // 检查并请求权限
        if (Build.VERSION.SDK_INT >= 23) {

            String[] permissions = { "android.permission.WRITE_EXTERNAL_STORAGE" };
            // 验证是否许可权限
            for (String str : permissions) {
                if (this.checkSelfPermission(str) != PackageManager.PERMISSION_GRANTED) {
                    // 申请权限
                    this.requestPermissions(permissions, REQUEST_CODE_CONTACT);
                    flag = false;
                }
            }
        }
        return flag;
    }

    @SuppressLint("NewApi")
    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        // 检查返回数据
        if (requestCode == REQUEST_CODE_CONTACT) {
            if (Build.VERSION.SDK_INT >= 23) {
                if (grantResults[0] != PackageManager.PERMISSION_GRANTED) {
                    show("表情包没有权限的话，就无法保存截图了哦");
                } else {
                    saveBitmap();
                }
            }
        }
    }

    /**
     * 保存截图
     */
    private void saveBitmap() {
        if (requestPermissions()) {
            if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
                File dir = new File(Environment.getExternalStorageDirectory(), "GameScreenShot");
                if (!dir.exists()) {
                    dir.mkdirs();
                }

                File file = new File(dir, time + ".jpg");
                OutputStream out = null;
                try {
                    out = new FileOutputStream(file);
                    while (out == null) {
                        out = new FileOutputStream(file);
                    }
                    App app = (App) getApplication();
                    app.screenShot.compress(Bitmap.CompressFormat.JPEG, 90, out);
                    show("已保存到" + file.getAbsolutePath());

                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    try {
                        out.flush();
                        out.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }

    /**
     * 在主线程显示Toast消息
     * 
     * @param text
     *            消息
     */
    private void show(final String text) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                Toast.makeText(EndActivity.this, text, Toast.LENGTH_SHORT).show();
            }
        });
    }

}
